package com.example.falvback.controller;

import cn.hutool.core.io.FileUtil;
import com.example.falvback.common.AuthAccess;
import com.example.falvback.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 功能：
 * 作者：chen
 * 日期：2023/11/1516:13
 */

@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${ip:localhost}")
    String ip;
    @Value("${server.port:9090}")
    String port;

    private static final String ROOT_PATH = System.getProperty("user.dir") + File.separator + "files";
//    @AuthAccess
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();//获取文件名
        String mainName = FileUtil.mainName(originalFilename);//获取文件名
        String extName = FileUtil.extName(originalFilename);//获取文件后缀名
//        File parentFile = FileUtil.mkdir(ROOT_PATH);//创建文件夹
        if(!FileUtil.exist(ROOT_PATH)){
            FileUtil.mkdir(ROOT_PATH);//若当前文件夹不存在，则创建
        }
        if(FileUtil.exist(ROOT_PATH+File.separator+originalFilename)){
            originalFilename = mainName+"_"+System.currentTimeMillis()+"."+extName;//若文件已存在，则重命名

        }
        File saveFile = new File(ROOT_PATH+File.separator+originalFilename);//创建文件
        file.transferTo(saveFile);//保存文件到本地
        String url = "http://"+ip+":"+port+"/file/download/"+originalFilename;//获取文件链接

        return Result.success(url);//返回文件链接
    }

    @AuthAccess
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {//加上@PathVariable注解，表示这是一个参数，否则会报错
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        String filePath = ROOT_PATH + File.separator + fileName;
        if(!FileUtil.exist(filePath)){
            return;
        }
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();

    }
}
